/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aruoc.sim;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import net.phys2d.math.MathUtil;
import net.phys2d.math.Matrix2f;
import net.phys2d.math.Vector2f;
import net.phys2d.raw.Body;
import net.phys2d.raw.BroadCollisionStrategy;
import net.phys2d.raw.World;
import org.aruoc.sim.siguelineas.Main;

/**
 *
 * @mperezma
 */
public class SimWorld extends World {

    public boolean upPressed;
    public boolean rightPressed;
    public boolean leftPressed;
    public boolean invertirDireccion = false;
    private List<Sim> sims = new ArrayList<Sim>();
    private BufferedImage imagen;
    private long currentFrame = 0;

    public SimWorld(Vector2f gravity, int iterations, URL urlTerreno) {
        super(gravity, iterations);
        inicializarTerreno(urlTerreno);
    }

    public long currentTime() {
        return currentFrame;
    }

    public KeyAdapter getKeyAdapter() {
        return new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                keyPress(e);
            }

            @Override
            public void keyReleased(KeyEvent e) {
                keyRelease(e);
            }
        };
    
    }

    private void keyPress(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            Main.executing = false;
            System.out.println("Terminando simulación...");
        }

        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            if (invertirDireccion) {
                rightPressed = true;
            } else {
                leftPressed = true;
            }

        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            if (invertirDireccion) {
                leftPressed = true;
            } else {
                rightPressed = true;
            }

        }
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            upPressed = true;
        }

    }

    private void keyRelease(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            if (invertirDireccion) {
                rightPressed = false;
            } else {
                leftPressed = false;
            }

        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            if (invertirDireccion) {
                leftPressed = false;
            } else {
                rightPressed = false;
            }
        }
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            upPressed = false;
        }

    }

    /**
     * 
     * @param gravity
     * @param iterations
     * @param strategy
     * @param friction 
     */
    public SimWorld(
            Vector2f gravity, int iterations, BroadCollisionStrategy strategy, URL urlTerreno) {
        super(gravity, iterations, strategy);
        inicializarTerreno(urlTerreno);
    }

    private void inicializarTerreno(URL url) {
        try {
            // Read from a file
            //URL url = this.getClass().getResource("imagen.gif");            
            imagen = ImageIO.read(url);
            //System.out.println("Imagen: " + getImagen());

            // Read in a buffered image
            //File file = new File("imagen.gif");
            //ImageInputStream iis = ImageIO.createImageInputStream(file);
            ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
            ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
            reader.setInput(iis, true);
            imagen = reader.read(0);

//            for (int i = 200; i < 500; i++) {
//                for (int ii = 200; ii < 500; ii++) {
//                  //  System.out.println("Color pixel 0,0=" + imagen.getRGB(i, ii));
//                }
//            }

        //System.out.println("Reader: " + reader);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public Vector2f impulsar(Body cuerpo, float fuerza) {
        Matrix2f giro = new Matrix2f(cuerpo.getRotation());
        Vector2f aceleracion = new Vector2f(0.0f, fuerza);
        Vector2f direccionAvance = MathUtil.mul(giro, aceleracion);
        cuerpo.addForce(direccionAvance);
        return direccionAvance;
    }

    void addSim(Sim sim) {
        sims.add(sim);
    }

    Iterable<Sim> getSims() {
        return sims;
    }

    private void aplicarRozamientos() {
        for (int i = 0; i < bodies.size(); i++) {

            Body body = bodies.get(i);

            if (body instanceof SimContacto) {
                ((SimContacto) body).step(this);
            }
        }

    }

    @Override
    public void step() {
        aplicarRozamientos();
        for (Sim sim : sims) {
            sim.step();
        }
        super.step();
        currentFrame++;
    }

    public BufferedImage getImagen() {
        return imagen;
    }

    public void setImagen(BufferedImage imagen) {
        this.imagen = imagen;
    }

}
